package com.wangwei.authoritySystem.config.security;

/**
 * 登录成功处理器
 */
import cn.hutool.json.JSONUtil;
import com.wangwei.authoritySystem.common.utils.JwtUtils;
import com.wangwei.authoritySystem.common.utils.LoginResult;
import com.wangwei.authoritySystem.config.redis.RedisService;
import com.wangwei.authoritySystem.pojo.User;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
 * 登录认证成功处理器类
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        //设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        //获取当登录用户信息
        User user = (User) authentication.getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(user);
        //设置token签名及过期时间
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())//签名密钥
                .parseClaimsJws(token.replace("jwt_",""))
                .getBody().getExpiration().getTime();//过期时间
        //创建loginResult登录结果对象
        LoginResult loginResult = new LoginResult(user.getId(),200,token,expireTime);
        String result = JSONUtil.toJsonStr(loginResult);
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        //token信息保存到redis
        String tokenKey = "token_"+token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration()/1000);
    }
}
